package controllers

import "LoginTemplate/models"

type MarketController struct {
	BaseController
}

type Market struct {
	ID         int    `json:"id"`
	MarketId   int    `json:"market_id"`
	MarketName string `json:"market_name"`
}

// 添加分类
func (u *MarketController) InsertMarket() {
	var market Market
	err := u.ShouldBind(&market)
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "insert into market ( id,market_id,market_name) values (?,?,?)"
	tx := models.DB.Debug().Exec(sql, market.ID, market.MarketId, market.MarketName)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

// 修改分类
func (u *MarketController) UpdateMarket() {
	var market Market
	err := u.ShouldBind(&market)
	if err != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "update market set market_id = ?,market_name = ? where id = ?"
	tx := models.DB.Debug().Exec(sql, market.MarketId, market.MarketName, market.ID)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

type MarketData struct {
	Code        int      `json:"code"`
	Msg         string   `json:"msg"`
	Data        []Market `json:"data"`
	Sum         int      `json:"sum"`         //总页数
	CurrentPage int      `json:"currentPage"` //当前页
	TotalNumber int      `json:"totalNumber"` //总条数
}

// 查询分类
func (u *MarketController) SelectMarket() {
	var pictureList PictureList
	err := u.ShouldBind(&pictureList)
	var sum int
	var totalNumber int
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var client []Market
	sql := "select * from market limit ? , ?"
	tx := models.DB.Debug().Raw(sql, (pictureList.Page-1)*pictureList.Size, pictureList.Size).Scan(&client)
	sqlsum := "SELECT CEIL(COUNT(*) / ? ) FROM market"
	models.DB.Debug().Raw(sqlsum, pictureList.Size).Scan(&sum)
	sqlNumBer := "select count(*) from market"
	models.DB.Debug().Raw(sqlNumBer).Scan(&totalNumber)
	if tx.Error != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var picturedata MarketData
	picturedata.Code = 200
	picturedata.Data = client
	picturedata.Msg = "成功"
	picturedata.Sum = sum
	picturedata.CurrentPage = pictureList.Page
	picturedata.TotalNumber = totalNumber
	//return picturedata
	u.JsonMsg(200, map[string]interface{}{
		"list":  picturedata,
		"count": "",
	}, "success")
}
